import { useEffect, useMemo, useState } from "react";
import { Button, Card, Drawer, Form, Input, Space } from "antd";
import Table, { type ColumnsType } from "antd/es/table";
import seriesService, {type PageListReq } from "@/api/services/base/seriesService";
import { TableToolbar } from "@/components/grid/TableToolbar";
import type { ProductSeries } from "./entity";
import { toast } from "sonner";
import { t } from "@/locales/i18n";


export default function ProductSeriesPage() {
    const [loading, setLoading] = useState(false);
    const [queryParams, setQueryParams] = useState<PageListReq>({
        name: undefined,
        page: 1,
        pageSize: 10,
    });
    const [total, setTotal] = useState(0);
    const [list, setList] = useState<ProductSeries[]>([]);
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    const [tableSize, setTableSize] = useState<"large" | "middle" | "small">("middle");
    const [drawerVisible, setDrawerVisible] = useState(false);
    const [editingData, setEditingData] = useState<ProductSeries | null>(null);
    const [form] = Form.useForm();
    const [isView, setIsView] = useState(true); // 控制表单禁用状态

    // 定义表格列
    const columns: ColumnsType<ProductSeries> = [
        {
            title: "系列",
            key: "name",
            dataIndex: "name",
        },
        {
            title: "描述",
            key: "remark",
            dataIndex: "remark",
        },
        {
            title: "操作",
            key: "operation",
            align: "center",
            width: 100,
            render: (_, record) => (
                <Space>
                    <Button type="link" onClick={() => handleView(record)}>
                        {t("common.view")}
                    </Button>
                    <Button type="link" onClick={() => handleEdit(record)}>
                        {t("common.edit")}
                    </Button>
                </Space>
            ),
        },
    ];

    // 状态管理
    const [selectedValues, setSelectedValues] = useState<string[]>(() =>
        columns.filter((col) => col.key !== "operation").map((col) => String(col.key!)),
    );

    // 处理过滤后的列配置
    const filteredColumns = useMemo(() => {
        return [
            // 显示选中的列
            ...columns.filter(
                (col) => selectedValues.includes(String(col.key)) || col.key === "operation", // 始终包含操作列
            ),
        ].sort((a, b) => {
            // 保持原始顺序
            const originalIndex = columns.findIndex((c) => c.key === a.key);
            const targetIndex = columns.findIndex((c) => c.key === b.key);
            return originalIndex - targetIndex;
        });
    }, [selectedValues]);

    const fetchPageList = () => {
        setLoading(true);
            seriesService.pageList(queryParams).then(res => {
            setList(res.records);
            setTotal(res.total);
        }).catch((error) => {
            console.log(error);
            toast.error("获取数据失败！", error)
        }).finally(()=>{
            setLoading(false);
        });
    };

    //组件加载时获取组织机构数据
    useEffect(() => {
        fetchPageList();
    }, [queryParams]);

    //触发分页控件
    const handlePageChange = (newPage: number, newPageSize: number) => {
        setQueryParams((prev) => ({
            ...prev,
            page: newPage,
            pageSize: newPageSize,
        }));
    };

    const handleEdit = (productSeries: ProductSeries) => {
        setEditingData(productSeries);
        form.setFieldsValue(productSeries);
        setDrawerVisible(true);
        setIsView(false);
    };

    /**
     * 查看产品系列
     * @param productSeries 产品系列
     */
    const handleView = (productSeries: ProductSeries) => {
        setEditingData(productSeries);
        form.setFieldsValue(productSeries);
        setIsView(true);
        setDrawerVisible(true);
    };

    const handleSubmit = async (values) => {
        try {
            setLoading(true);
            if (editingData) {
                await seriesService.update({ ...values, id: editingData.id });
                toast.success("更新产品系列成功");
            } else {
                await seriesService.add(values);
                toast.success("创建产品系列成功");
            }
            setDrawerVisible(false);
            setEditingData(null);
            form.resetFields();
            fetchPageList();
        } catch (error) {
            toast.error(`${error.message}`);
        } finally {
            setLoading(false);
        }
    };

    const handleDrawerClose = () => {
        setDrawerVisible(false);
        setEditingData(null);
        form.resetFields();
    };

    const handleAdd = () => {
        setEditingData(null);
        form.resetFields();
        setDrawerVisible(true);
        setIsView(false);
    };

    //删除产品系列方法
    const handleDelete = async () => {
        try {
            setLoading(true);
            await seriesService.remove(selectedRowKeys);
            toast.success("删除产品系列成功");
            setSelectedRowKeys([]); // 清空选中项
            fetchPageList(); // 重新加载列表
        } catch (error) {
            toast.error(`删除失败: ${error.message}`);
        } finally {
            setLoading(false);
        }
    };

    return (
        <>
            {/* 查询条件 */}
            <Card className="mb-4">
                <Form
                    layout="inline"
                    onFinish={(values) => {
                        // 处理查询条件
                        setQueryParams((prev) => ({
                            ...prev,
                            ...values,
                            page: 1,
                        }));
                    }}
                >
                    <Form.Item name="name" label="系列">
                        <Input placeholder="请输入系列" allowClear />
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit">
                            查询
                        </Button>
                        <Button
                            className="ml-2"
                            onClick={() => {
                                // 重置查询条件
                                setQueryParams({ page: 1, pageSize: 10 });
                            }}
                        >
                            重置
                        </Button>
                    </Form.Item>
                </Form>
            </Card>
            <div className="h-4" />
            {/* 表格数据 */}
            <Card>
                <div className="flex justify-between mb-4">
                    <div className="flex gap-2">
                        <Button type="primary" onClick={handleAdd}>
                            新增
                        </Button>
                        <Button danger disabled={selectedRowKeys.length === 0} onClick={handleDelete}>
                            删除
                        </Button>
                    </div>
                    <TableToolbar
                        onRefresh={() => setQueryParams((prev) => ({ ...prev }))}
                        onSizeChange={setTableSize}
                        columns={columns}
                        selectedValues={selectedValues}
                        onColumnChange={setSelectedValues}
                    />
                </div>
                <Table
                    rowKey="id"
                    size={tableSize}
                    scroll={{ x: "max-content" }}
                    loading={loading}
                    pagination={{
                        total,
                        current: queryParams.page,
                        pageSize: queryParams.pageSize,
                        onChange: handlePageChange,
                    }}
                    columns={filteredColumns}
                    dataSource={list}
                    rowSelection={{
                        type: "checkbox",
                        selectedRowKeys: selectedRowKeys,
                        onChange: (selectedKeys) => {
                            setSelectedRowKeys(selectedKeys as string[]);
                        },
                    }}
                />
            </Card>
            {/* 编辑页面 */}
            <Drawer
                title={editingData ? "编辑产品系列" : "新增产品系列"}
                width={480}
                open={drawerVisible}
                onClose={handleDrawerClose}
                footer={
                    <div className="flex justify-end gap-2">
                        <Button onClick={handleDrawerClose}>取消</Button>
                        {!isView && (
                            <Button type="primary" onClick={() => form.submit()}>
                                确定
                            </Button>
                        )}
                    </div>
                }
            >
                <Form form={form} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} onFinish={handleSubmit} disabled={isView}>
                    <Form.Item name="name" label="系列">
                        <Input placeholder="请输入系列"/>
                    </Form.Item>
                    <Form.Item name="remark" label="描述">
                        <Input placeholder="请输入描述"/>
                    </Form.Item>
                </Form>
            </Drawer>
        </>
    );
}
